package com.bd.volkswagen.controller;


import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
//import com.bd.offices.excel.ExcelUtil;
import com.bd.scm.core.toolkit.SwaggerConstants;
import com.bd.scm.domain.dto.aggrid.AgGridRequest;
import com.bd.scm.domain.dto.aggrid.AgGridResponse;
import com.bd.scm.domain.dto.leave.BdLeaveOrderSerachDto;
import com.bd.scm.domain.dto.leave.LeaveFailDto;
import com.bd.scm.domain.dto.user.PersonnelFilesDto;
import com.bd.scm.domain.dto.user.UserDto;
import com.bd.scm.domain.dto.user.UserInfoBaseDto;
import com.bd.scm.domain.dto.user.UserOfLeaveBatchDto;
import com.bd.scm.domain.models.user.DtUser;
import com.bd.scm.domain.models.user.UserInfo;
import com.bd.scm.domain.models.user.UserVacation;
import com.bd.scm.module.enums.ExceptionEmun;
import com.bd.scm.module.user.service.IDtUserService;
import com.bd.scm.module.common.BaseController;
//import com.bd.scm.module.user.service.IUserViewService;
//import com.bd.scm.module.user.service.UserInfoService;
import com.bd.scm.module.utils.ResultUtil;
import com.bd.utils.FileUtil;
import com.bd.utils.vo.Result;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户前端控制器
 * User: _Cps
 * Date: 2019.08.28 16:44
 */
@Slf4j
@RestController
@RequestMapping("/api/user")
public class UserController extends BaseController {

    @Resource
    private IDtUserService iDtUserService;

//    @Autowired
//    private UserInfoService userInfoService;
//
//    @Autowired
//    private IUserViewService iUserViewService;

//    /**
//     * @param userDto
//     * @return
//     */
//    @PostMapping("list")
//    @ApiOperation(value = "根据部门树获取员工列表", httpMethod = "POST", protocols = "HTTP", notes = "根据部门树获取员工列表", produces =
//            "application/json")
//    public Result getUserList(
//            @ApiParam(name = "userDto", value = "员工请求Dto", required = true)
//            @RequestBody UserDto userDto
//    ) {
//        System.out.println("<<<<<" + JSONArray.toJSONString(userInfoService.getUserList(userDto)));
//        return ResultUtil.ok(userInfoService.getUserList(userDto));
//    }

    /**
     * AgGridResponse
     *
     * @param request
     * @return
     */
//    @PostMapping("userList")
//    @ApiOperation(value = "根据部门树获取员工列表", httpMethod = "POST", protocols = "HTTP", notes = "根据部门树获取员工列表", produces =
//            "application/json")
//    public Result<AgGridResponse> userList(
//            @ApiParam(name = "userDto", value = "员工请求Dto", required = true)
//            @RequestBody AgGridRequest request
//    ) {
//        Result<AgGridResponse> result = new Result<AgGridResponse>();
//        //Page<UserInfo> page = new Page<UserInfo>(userDto.getCurrent(),userDto.getPageSize());
//        Page<UserInfo> page = getPage(request);
//        System.err.println(JSON.toJSON(request));
//
//        IPage<UserInfo> pageList = userInfoService.getUserList(null);
//        AgGridResponse<UserInfo> response = getResponse(request, pageList, page);
//        result.setSuccess(true);
//        result.setResult(response);
//        return result;
//    }

//    @PostMapping("list/agList")
//    @ApiOperation(value = "根据条件获取员工列表", httpMethod = "POST", protocols = "HTTP", notes = "根据条件获取员工列表", produces =
//            "application/json")
//    public Result getUserListByParam(
//            @ApiParam(name = "userDto", value = "员工查询条件", required = true)
//            @RequestBody UserDto userDto
//    ) {
//        log.info(String.valueOf(userDto));
//        return ResultUtil.ok(userInfoService.getUserListByParam(userDto));
//    }

    /**
     * 获取人员（包含假期额度数据）.
     *
     * @param userOfLeaveBatchDto
     * @return
     */
    @PostMapping("getUserInfoList")
    public Result getUserInfoList(@RequestBody UserOfLeaveBatchDto userOfLeaveBatchDto) {

        return ResultUtil.ok(iDtUserService.getUserInfoList(userOfLeaveBatchDto));

    }

    /**
     * 获取人员（结合工作日历）.
     *
     * @param userOfLeaveBatchDto
     * @return
     */
    @PostMapping("getUserCalendarInfoList")
    public Result getUserCalendarInfoList(@RequestBody UserOfLeaveBatchDto userOfLeaveBatchDto) {

        return ResultUtil.ok(iDtUserService.getUserCalendarInfoList(userOfLeaveBatchDto));

    }

    /**
     * 获取人员（包含假期额度数据）.
     *
     * @param userOfLeaveBatchDto
     * @return
     */
    @PostMapping("getLoginerInfoList")
    public Result getLoginerInfoList(HttpServletRequest request, @RequestBody UserOfLeaveBatchDto userOfLeaveBatchDto) {
        System.out.println("Session ID:"+request.getSession().getId());
        JSONObject user = (JSONObject) request.getSession().getAttribute("user");
        if (ObjectUtil.isNull(user)) {
            log.error("user session is empty.");
            return ResultUtil.error("用户未登录");
        }
        userOfLeaveBatchDto.setUserIds(user.getString("userSerial"));
        return ResultUtil.ok(iDtUserService.getUserInfoList(userOfLeaveBatchDto));
    }

    /**
     * 分页获取人员信息.
     *
     * @return 人员信息集合
     */
    @GetMapping("getUserList")
    public Result getUserList(Integer pageNumber, Integer pageSize, PersonnelFilesDto personnelFilesDto) {
        Result result = null;
        try {
            Page<PersonnelFilesDto> page = new Page<>(pageNumber, pageSize);
            IPage<PersonnelFilesDto> pageList = this.iDtUserService.getUserList(page, personnelFilesDto);
            result = ResultUtil.ok(pageList);
        } catch (Exception e) {
            e.printStackTrace();
            result = ResultUtil.error("获取数据失败");
        }
        return result;
    }

    /**
     * 分页同步差异人员信息.
     *
     * @return 人员信息集合
     */
    @RequestMapping("getManualUserList")
    public Result getManualUserList(@RequestBody PersonnelFilesDto personnelFilesDto) {
        Result result = null;
        try {
            result = Result.ok(this.iDtUserService.getManualUserList(personnelFilesDto));
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("程序内部错误");
        }
        return result;
    }

    /**
     * 新增
     *
     * @param personnelFilesDto 条件
     * @return
     */
    @RequestMapping("/addUserInfo")
    @ResponseBody
    public Result addUserInfo(@RequestBody PersonnelFilesDto personnelFilesDto, HttpServletRequest request) throws UnknownHostException {
        String clientIp = InetAddress.getLocalHost().getHostAddress();
        JSONObject users = (JSONObject) request.getSession().getAttribute("user");
        personnelFilesDto.setGlyNo(users.getString("userSerial"));
        PersonnelFilesDto user = this.iDtUserService.addUserInfo(personnelFilesDto, clientIp);

        return user == null ? ResultUtil.error(ExceptionEmun.USER_ERROR_NAMEREPETITION) : ResultUtil.ok(user);
    }

    /**
     * 修改
     *
     * @param personnelFilesDto 条件
     * @return
     */
    @RequestMapping("/updateUserInfo")
    @ResponseBody
    public Result updateUserInfo(@RequestBody PersonnelFilesDto personnelFilesDto, HttpServletRequest request) throws UnknownHostException {
        String clientIp = InetAddress.getLocalHost().getHostAddress();
        JSONObject user = (JSONObject) request.getSession().getAttribute("user");
        personnelFilesDto.setGlyNo(user.getString("userSerial"));
        int flag = this.iDtUserService.updateUserInfo(personnelFilesDto, clientIp);
        if (flag > 0) {
            return ResultUtil.ok();
        } else {
            return ResultUtil.error(ExceptionEmun.USER_ERROR_NAMEREPETITION);
        }
    }

    /**
     * 离职
     *
     * @param
     * @return
     */
    @RequestMapping("/quitUserInfo")
    @ResponseBody
    public Result quitUserInfo(@RequestBody UserVacation userVacation) throws UnknownHostException {
        String userSerial = userVacation.getUserSerial();
        String clientIp = InetAddress.getLocalHost().getHostAddress();
        int flag = this.iDtUserService.quitUserInfo(userSerial, clientIp);
        if (flag > 0) {
            return ResultUtil.ok();
        } else {
            return ResultUtil.error(ExceptionEmun.USER_ERROR_Quit);
        }
    }

    /**
     * 临时借调
     *
     * @param personnelFilesDto 条件
     * @return
     */
    @RequestMapping("/addLoanInfo")
    @ResponseBody
    public Result addLoanInfo(@RequestBody PersonnelFilesDto personnelFilesDto) throws UnknownHostException {
        String clientIp = InetAddress.getLocalHost().getHostAddress();
        int flag = this.iDtUserService.addLoanInfo(personnelFilesDto, clientIp);
        if (flag > 0) {
            return ResultUtil.ok();
        } else {
            return ResultUtil.error(ExceptionEmun.SERVICE_ERROR);
        }
    }

    /**
     * 调动
     *
     * @param personnelFilesDto 条件
     * @return
     */
    @RequestMapping("/transferPerson")
    @ResponseBody
    public Result transferPerson(@RequestBody PersonnelFilesDto personnelFilesDto, HttpServletRequest request) throws UnknownHostException {
        String clientIp = InetAddress.getLocalHost().getHostAddress();
        JSONObject user = (JSONObject) request.getSession().getAttribute("user");
        personnelFilesDto.setGlyNo(user.getString("userSerial"));
        String flag = this.iDtUserService.transferPerson(personnelFilesDto.getBeginTime(),
                personnelFilesDto.getUserSerial(), personnelFilesDto.getDepSerial(), personnelFilesDto.getGlyNo(),
                clientIp, "1");
        if (null != flag) {
            return ResultUtil.error(flag);
        } else {
            return ResultUtil.ok();
        }
    }


    /**
     * 获取身份证号获取人员信息
     */
    @RequestMapping("infoByIdCard")
    @ResponseBody
    public Result getUserInfoByCardId(String userId) {
        DtUser userInfoByCardId = this.iDtUserService.getUserInfoByCardId(userId);
        if (userInfoByCardId != null && !userInfoByCardId.equals("")) {
            return ResultUtil.ok(userInfoByCardId);
        } else {
            return ResultUtil.error(ExceptionEmun.SERVICE_ERROR_NODATA);
        }

    }


    /**
     * 获取人员编号
     */
    @RequestMapping("getUserSerial")
    @ResponseBody
    public Result getUserSerial() {
        return ResultUtil.ok(this.iDtUserService.getUserSerialAndNo());
    }


    /**
     * 获取账户类型.
     *
     * @param
     * @return 账户类型信息
     */
    @RequestMapping("getacTypeList")
    @ResponseBody
    public Result getacTypeList() {
        List<PersonnelFilesDto> list = this.iDtUserService.getacTypeList();
        return ResultUtil.ok(list);
    }

    /**
     * 获取民族信息.
     *
     * @param
     * @return 民族信息
     */
    @RequestMapping("getNationList")
    @ResponseBody
    public Result getNation() {
        return ResultUtil.ok(this.iDtUserService.getNation());
    }

    /**
     * 获取籍贯信息.personFilesService
     *
     * @param
     * @return 籍贯信息
     */
    @RequestMapping("getNativeList")
    @ResponseBody
    public Result getNative() {
        return ResultUtil.ok(this.iDtUserService.getNative());
    }

    /**
     * 获取档案类型
     */
    @RequestMapping("getUserType")
    @ResponseBody
    public Result getUserType() {
        return ResultUtil.ok(this.iDtUserService.getUserType());
    }

    /**
     * 考勤打卡类型
     */
    @RequestMapping("getkqdkLxList")
    @ResponseBody
    public Result getkqdkLxList() {
        return ResultUtil.ok(this.iDtUserService.getkqdkLxList());
    }

    /**
     * 就餐类型
     */
    @RequestMapping("getjcLxList")
    @ResponseBody
    public Result getjcLxList() {
        return ResultUtil.ok(this.iDtUserService.getjcLxList());
    }


    /**
     * 导入
     *
     * @param file
     * @param request
     * @return
     * @throws
     */
    @RequestMapping("uploadingExcel")
    @ResponseBody
    public Result uploadingExcel(MultipartFile file, HttpServletRequest request) throws Exception {
        String flag = this.iDtUserService.uploadingExcel(file, request);
        if (null != flag) {
            return ResultUtil.error(flag);
        } else {
            return ResultUtil.ok();
        }
    }

    /**
     * 人员同步
     *
     * @param
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping("userSynchronization")
    public Result userSynchronization() throws Exception {
        String flag = this.iDtUserService.userSynchronization();
        if (null != flag) {
            return ResultUtil.error(flag);
        } else {
            return ResultUtil.ok();
        }
    }

    /**
     * 部门同步
     *
     * @param
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping("deptSynchronization")
    public Result deptSynchronization() throws Exception {
        String flag = this.iDtUserService.deptSynchronization();
        if (null != flag) {
            return ResultUtil.error(flag);
        } else {
            return ResultUtil.ok();
        }
    }

    /**
     * 手动同步人员信息
     *
     * @param personnelFilesDto 条件
     * @return
     */
    @RequestMapping("/manualSynUserInfo")
    @ResponseBody
    public Result manualSynUserInfo(@RequestBody PersonnelFilesDto personnelFilesDto) throws UnknownHostException {
        String clientIp = InetAddress.getLocalHost().getHostAddress();
        int flag = this.iDtUserService.manualSynUserInfo(personnelFilesDto.getUserNo(), clientIp);
        if (flag > 0) {
            return ResultUtil.ok();
        } else {
            return ResultUtil.error(ExceptionEmun.SERVICE_ERROR);
        }
    }


    /**
     * 根据登录人获取第一级审批人 批量.
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("getApproverListByBatch")
    public Result getApproverListByBatch(HttpServletRequest request) {
        Result result = null;
        try {
            JSONObject user = (JSONObject) request.getSession().getAttribute("user");
            result = Result.ok(iDtUserService.getApproverListByBatch(user.getString("userSerial")));
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("程序内部错误");
        }
        return result;
    }

    /**
     * 根据登录人获取第二级审批人 批量.
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("getSecondListByBatch")
    public Result getSecondListByBatch(HttpServletRequest request) {
        Result result = null;
        try {
            JSONObject user = (JSONObject) request.getSession().getAttribute("user");
            result = Result.ok(iDtUserService.getSecondListByBatch(user.getString("userSerial")));
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("程序内部错误");
        }
        return result;
    }

    /**
     * 人员导入模板
     *
     * @param response
     * @param request
     * @throws IOException
     */
    @RequestMapping(value = "/downLoadTemplate3")
    public void downLoad3(HttpServletResponse response, HttpServletRequest request) throws IOException {
        String fileName = "人员导入模板" + ".xlsx";
        ServletOutputStream out;
        FileUtil.setResponseHeader(fileName, response);
        String filePath = getClass().getResource("/downLoadTemplate/" + fileName).getPath();
        filePath = URLDecoder.decode(filePath, "UTF-8");
        FileInputStream inputstream = new FileInputStream(filePath);
        out = response.getOutputStream();
        int b = 0;
        byte[] buffer = new byte[1024];
        while ((b = inputstream.read(buffer)) != -1) {
            // 4.写到输出流(out)中
            out.write(buffer, 0, b);
        }
        inputstream.close();

        if (out != null) {
            out.flush();
            out.close();
        }
    }

    /**
     * 人员导出
     *
     * @param serchTxt
     * @param response
     * @return
     * @throws IOException
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    @RequestMapping(value = "userExport")
    public Result vacationExport(String serchTxt, String depSerial, HttpServletResponse response) throws IOException,
            InstantiationException, IllegalAccessException {
        PersonnelFilesDto personnelFilesDto = new PersonnelFilesDto();
        personnelFilesDto.setSerchTxt(serchTxt);
        personnelFilesDto.setDepSerial(depSerial);
        AgGridRequest request = new AgGridRequest();
        request.setStartRow(0);
        request.setEndRow(10000);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("serchTxt", serchTxt);
        map.put("depSerial", depSerial);
        request.setData(map);
        Page<PersonnelFilesDto> page = getPage(request);
        List<PersonnelFilesDto> doorDefinition = this.iDtUserService.getUserList(page, personnelFilesDto).getRecords();
//        ExcelUtil.ExportExcel("导出人员列表", response, doorDefinition, PersonnelFilesDto.class);
        return ResultUtil.ok();
    }

    @RequestMapping(value = "/getUserCompany")
    public Result getUserCompany() {
        Result result = null;
        try {
            List<String> list = this.iDtUserService.getUserCompany();
            result = ResultUtil.ok(list);
        } catch (Exception e) {
            e.printStackTrace();
            result = ResultUtil.error("获取所属公司集合失败");
        }
        return result;
    }

    @RequestMapping(value = "/getUserSnyLx")
    public Result getUserSnyLx() {
        Result result = null;
        try {
            List<String> list = this.iDtUserService.getUserSnyLx();
            result = ResultUtil.ok(list);
        } catch (Exception e) {
            e.printStackTrace();
            result = ResultUtil.error("获取员工类型集合失败");
        }
        return result;
    }

//    @RequestMapping(value = "/getUserSnyType")
//    public Result getUserSnyType() {
//        Result result = null;
//        try {
//            List<String> list = this.iDtUserService.getUserSnyType();
//            result = ResultUtil.ok(list);
//        } catch (Exception e) {
//            e.printStackTrace();
//            result = ResultUtil.error("获取员工状态集合失败");
//        }
//        return result;
//
//    }

    /**
     * 查询所有工作日历.
     *
     * @param
     * @return 查询所有工作日历信息
     */
//    @RequestMapping("findBdKqWorkCalendarList")
//    @ResponseBody
//    public Result findBdKqWorkCalendarList() {
//        List<JSONObject> list = this.iDtUserService.findBdKqWorkCalendarList();
//        return ResultUtil.ok(list);
//    }

    /**
     * 根据工号姓名部门模糊查找员工
     *
     * @param userDto
     * @param request
     * @return
     */
//    @ApiOperation(value = "根据工号姓名部门模糊查找员工", httpMethod = "POST", protocols = "HTTP", notes = "根据工号姓名部门模糊查找员工",
//            produces = "application/json")
//    @PostMapping("app/query/nnd")
//    public Result getListByNoNameDept(
//            @ApiParam(name = "UserDto", value = "查询条件", required = true)
//            @RequestBody UserDto userDto, HttpServletRequest request) {
//        //TODO 当前部门权限查询
//
//        IPage<UserInfoBaseDto> list = iUserViewService.getListByNoNameDept(userDto);
//
//        return Result.ok(list);
//    }

//    @PostMapping("list/userListByTree")
//    @ApiOperation(value = "根据条件获取员工列表", httpMethod = "POST", protocols = "HTTP", notes = "根据条件获取员工列表", produces =
//            "application/json")
//    public Result getUserListByTree(
//            @ApiParam(name = "userDto", value = "员工查询条件", required = true)
//            @RequestBody UserDto userDto
//    ) {
//        log.info(String.valueOf(userDto));
//        return ResultUtil.ok(userInfoService.getUserListByTree(userDto));
//    }


    /**
     * 部门人员设置工作日历
     *
     * @return
     */
//    @RequestMapping("/setUserCalendar")
//    @ResponseBody
//    public Result setUserCalendar(@RequestBody PersonnelFilesDto personnelFilesDto, HttpServletRequest request) throws UnknownHostException {
//        String clientIp = InetAddress.getLocalHost().getHostAddress();
//        JSONObject user = (JSONObject) request.getSession().getAttribute("user");
//        personnelFilesDto.setGlyNo(user.getString("userSerial"));
//        personnelFilesDto.setLogIp(clientIp);
//        String flag = this.iDtUserService.setUserCalendar(personnelFilesDto);
//        if (flag == null) {
//            return ResultUtil.ok();
//        } else {
//            return ResultUtil.error(flag);
//        }
//    }

    /**
     * 获取职务列表.
     *
     * @return
     */
//    @GetMapping("/getJobGrade")
//    public Result getJobGrade() {
//        return ResultUtil.ok(iDtUserService.getJobGrade());
//
//    }

    /**
     * 获取岗位级别列表.
     *
     * @return
     */
    @GetMapping("/getTechnologicalJob")
    public Result getTechnologicalJob() {
        return ResultUtil.ok(iDtUserService.getTechnologicalJob());

    }

    @GetMapping("/byUserNo")
    public Result getUserInfoByUserNo(@RequestParam("userNo") String userNo) {
        return ResultUtil.ok(iDtUserService.getUserInfoByUserNo(userNo));

    }
}
